<template>
  <view class="topic">
    <view class="question">{{ topic.question }}</view>
    <view class="info">
      <text class="difficulty">难度：{{ topic.difficulty }}</text>
      <text class="views">学习次数：{{ topic.views }}</text>
    </view>
    <view class="answer">
      <image :src="topic.cover" mode="aspectFit"></image>
      <rich-text :nodes="htmlAnswer" class="content"></rich-text>
    </view>
  </view>
</template>
<script>
import { fetchData, md, STUDY_HISTORY } from "../../utils";
export default {
  name: "detail",
  data() {
    return {
      topic: {},
    };
  },
  async onLoad({ id }) {
    const topic = await fetchData({
      url: `/topic/${id}`,
      method: "GET",
    });
    this.topic = topic;
    this.addTopicToStudyHistory(topic);
    uni.setNavigationBarTitle({
      title: topic.question,
    });
  },
  methods: {
    addTopicToStudyHistory(topic) {
      let studyHistory = uni.getStorageSync(STUDY_HISTORY) || [];
      topic.studyTime = Date.now();
      const existingTopicIndex = studyHistory.findIndex(
        (item) => item.id === topic.id
      );
      if (existingTopicIndex !== -1) {
        studyHistory.splice(existingTopicIndex, 1);
      }
      studyHistory.unshift(topic);
      uni.setStorageSync(STUDY_HISTORY, studyHistory);
    },
  },

  computed: {
    htmlAnswer() {
      return md.render(this.topic.answer || "");
    },
  },
};
</script>

<style lang="scss">
.topic {
  padding: 20rpx;
  background-color: #fafafa;

  .question {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
    color: #333;
    text-align: center;
    background: #fff;
    padding: 20rpx;
    border-radius: 15rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  }

  .info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;
    background: #fff;
    padding: 20rpx;
    border-radius: 15rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .difficulty,
    .views {
      font-size: 28rpx;
      color: #777;
    }
  }

  .answer {
    margin-top: 20rpx;

    image {
      width: 100%;
      height: 400rpx;
      object-fit: cover;
      border-radius: 15rpx;
      margin-bottom: 20rpx;
    }

    .content {
      /deep/ ol,
      /deep/ ul {
        list-style-position: inside;
      }
      /deep/ code.language-html {
        white-space: pre-wrap;
        word-wrap: break-word;
      }
    }
  }
}
</style>
